package com.gitee.cui.concurrency.designmodel.forkjoin;

import com.gitee.cui.util.Print;

import java.util.concurrent.RecursiveTask;

/**
 * 计算数据加和的递归类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/12/9 9:16
 **/
public class AccumulateTask extends RecursiveTask<Integer> {

    private static final int THRESHOLD = 7;

    /**
     * 累加的起始数值
     */
    private int start;

    /**
     * 累加的结束数值
     */
    private int end;

    public AccumulateTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        // 判断是否需要直接结算结果
        boolean canCompute = (end - start) <= THRESHOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
            Print.tcfo("执行任务：计算" + start + "到" + end +"的和，结果是：" + sum);
        } else {
            Print.tcfo("切割任务：将" + start + "到" + end + "的和一分为二");
            // 将大任务一分为二
            int middle = (start + end) / 2;
            // 创建两个计算任务
            AccumulateTask lTask = new AccumulateTask(start, middle);
            AccumulateTask rTask = new AccumulateTask(middle + 1, end);
            // 对任务进行fork-join操作
            lTask.fork();
            rTask.fork();
            // 等待任务执行完成，获取每个子任务的结果
            Integer lResult = lTask.join();
            Integer rResult = rTask.join();
            // 合并子任务的结果
            sum = lResult + rResult;
        }
        return sum;
    }
}
